<script lang="ts" setup>
import { onMounted } from 'vue';

import { Page } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { Card, message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getSettingUpload, putSettingUpload } from '#/api/admin/setting';
import { usePreferencesStore } from '#/store';

defineOptions({
  name: 'AdminSettingupload',
});
type FileTypesConfig = {
  [key: string]: {
    extensions: string;
    upload_max_filesize: string;
  };
};

type UploadConfig = {
  chunk_size: number;
  file_types: FileTypesConfig;
  max_files: number;
  upload_max_filesize: {
    [key: string]: number;
  };
};

function generateUploadMaxFilesizeFromExtensions(config: UploadConfig): {
  [key: string]: number;
} {
  const result: { [key: string]: number } = {};

  for (const typeConfig of Object.values(config.file_types)) {
    const maxSize = Number.parseInt(typeConfig.upload_max_filesize, 10);
    const extensions = typeConfig.extensions.split(',');

    extensions.forEach((extension) => {
      result[extension] = maxSize * 1024;
    });
  }

  return result;
}

const [Form, formApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      defaultValue: 20,
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'max_files',
      label: $t("admin.File Count"),
      help: $t("admin.Max files help"),
    },
    {
      component: 'Input',
      defaultValue: 512,
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'chunk_size',
      label: $t("admin.Chunk Size"),
      help: $t("admin.Chunk size help"),
    },
  ],
  actionWrapperClass: 'text-center',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
  showDefaultActions: false,
});

const [ImageForm, imageFormApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      defaultValue: 10_240,
      componentProps: {
        placeholder: $t("admin.Image Size"),
      },
      fieldName: 'upload_max_filesize',
      label: $t("admin.Image Size"),
      help: $t("admin.Image size help"),
    },
    {
      component: 'Input',
      defaultValue: 'jpg,jpeg,png,gif,bmp',
      componentProps: {
        placeholder: $t("admin.Image Type"),
      },
      fieldName: 'extensions',
      label: $t("admin.Image Type"),
      help: $t("admin.Image type help"),
    },
  ],
  showDefaultActions: false,
  actionWrapperClass: 'text-center',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
});

const [VideoForm, videoFormApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      defaultValue: 10_240,
      componentProps: {
        placeholder: $t('admin.Video Size'),
      },
      fieldName: 'upload_max_filesize',
      label: $t("admin.Video Size"),
      help: $t('admin.Video size help'),
    },
    {
      component: 'Input',
      defaultValue: 'mp4,avi,wmv,rm,rmvb,mkv',
      componentProps: {
        placeholder: $t("admin.Video Type"),
      },
      fieldName: 'extensions',
      label: $t("admin.Video Type"),
      help: $t("admin.Video type help"),
    },
  ],
  showDefaultActions: false,
  actionWrapperClass: 'text-center',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
});

const [AudioForm, audioFormApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Input',
      defaultValue: 10_240,
      componentProps: {
        placeholder: $t("admin.Audio Size")
      },
      fieldName: 'upload_max_filesize',
      label: $t("admin.Audio Size"),
      help: $t("admin.Audio size help"),
    },
    {
      component: 'Input',
      defaultValue: 'mp3,wma,wav',
      componentProps: {
        placeholder: $t("admin.Audio Type")
      },
      fieldName: 'extensions',
      label: $t("admin.Audio Type"),
      help: $t("admin.Audio type help"),
    },
  ],
  showDefaultActions: false,
  actionWrapperClass: 'text-center',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
});

const [FileForm, fileFormApi] = useVbenForm({
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: 10_240,
      componentProps: {
        placeholder: $t("admin.Attachment Size"),
      },
      fieldName: 'upload_max_filesize',
      label: $t("admin.Attachment Size"),
      help: $t("admin.Attachment size help"),
    },
    {
      component: 'Input',
      defaultValue: 'txt,pdf,doc,docx,xls,xlsx,ppt,pptx,zip,rar',
      componentProps: {
        placeholder: $t("admin.Attachment Type")
      },
      fieldName: 'extensions',
      label: $t("admin.Attachment Type"),
      help: $t('admin.Attachment type help'),
    },
  ],
  resetButtonOptions: { show: false },
  actionWrapperClass: 'text-center',
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-2',
});

const onSearch = async () => {
  // 从 API 获取设置数据
  const {
    data: { setting },
  } = await getSettingUpload();
  // 更新表单值
  formApi.setValues(setting);
  usePreferencesStore().uploadSetting = setting;

  imageFormApi.setValues(setting.file_types.image);
  videoFormApi.setValues(setting.file_types.video);
  audioFormApi.setValues(setting.file_types.audio);
  fileFormApi.setValues(setting.file_types.file);
};

async function onSubmit() {
  const formData = await formApi.getValues();
  const imageFormData = await imageFormApi.getValues();
  const videoFormData = await videoFormApi.getValues();
  const fileFormData = await fileFormApi.getValues();
  const audioFormData = await audioFormApi.getValues();
  const values: any = {
    ...formData,
    file_types: {
      image: imageFormData,
      video: videoFormData,
      file: fileFormData,
      audio: audioFormData,
    },
  };
  values.upload_max_filesize = generateUploadMaxFilesizeFromExtensions(values);
  const { msg } = await putSettingUpload(values);
  onSearch();

  message.success({
    content: msg,
  });
}

onMounted(() => {
  onSearch();
});
</script>

<template>
  <Page>
    <Card>
      <Form />
      <ImageForm />
      <VideoForm />
      <AudioForm />
      <FileForm />
    </Card>
  </Page>
</template>
